import React, { useState, useEffect } from 'react';
import { Button, Drawer } from 'antd';

import TRNotification from '#/utils/notification';
import { TRDefault } from '#/components/TRTheme/index.js';
import icon from '@/assets/img/plan_icon.png';
import { TjTable } from '@/pages/ETrade/components';
import { PageLoading } from '@/components/index.js';
import { export_json_to_excel } from '@/utils/fileExport.js';
import { HttpCode } from '#/utils/contacts.js';

import { columns_1, columns_2, tableStyles, keyMap } from '../helper';
import styles from './index.less';
import { queryDetailData } from '../services';
import moment from 'moment';

const DrawerComponent = ({ title, onPress, width = 1400, selectData = [] }) => {
  const [visible, setVisible] = useState(true);
  const [loading, setLoading] = useState(true);
  const [tableData, setTableData] = useState({});

  const _onClose = () => {
    setVisible(false);
    onPress({ index: 0 });
  };

  const getColumns = (columns) =>
    columns.map((t) => ({
      code: t[0],
      name: t[1],
      align: 'center',
      width: t[2],
      render: (v) => {
        return v ?? '-';
      },
    }));

  const getNewDataSource = (data) => {
    return Object.entries(data).map((t) => ({
      ...t[1],
      contractType: keyMap[t[0]],
    }));
  };

  /**请求 */
  const getData = async () => {
    setLoading(true);
    const params = {
      stationId: selectData?.stationId,
      month: moment(selectData?.month).format('YYYY-MM'),
      provinceId: selectData?.provinceId,
    };
    const res = await queryDetailData(params).catch(() => {});
    if (res.statusCode === HttpCode.SUCCESS) {
      setTableData({
        station: [res?.data?.initStats],
        contract: getNewDataSource(res?.data?.incomeFromContractTransfer),
      });
    }
    setLoading(false);
  };

  useEffect(() => {
    getData();
  }, []);

  const onExport = () => {
    let exportData = [];
    Object.values(tableData).map((t, i) => {
      const tableColumns = getColumns(!i ? columns_1 : columns_2);
      if (i) {
        exportData = exportData.concat([[], tableColumns.map((c) => c.name)]);
      }
      exportData = exportData.concat(t.map((c) => tableColumns.map(({ code }) => c[code] ?? '-')));
    });
    const params = {
      header: getColumns(columns_1).map((c) => (c.name?.props ? c.name.props.children[0] : c.name)),
      data: exportData,
      filename: `策略详情`,
    };
    export_json_to_excel(params);
  };

  return (
    <Drawer
      className={styles._drawer}
      title={
        <div className={styles.title}>
          <img src={icon} />
          <div className={styles.iconText}>{title}</div>
        </div>
      }
      width={width}
      onClose={_onClose}
      visible={visible}
    >
      {loading ? (
        <PageLoading />
      ) : (
        <div className={styles.content}>
          <div className={styles.content_title}>初始统计</div>
          {tableData?.station?.length ? (
            <TjTable
              style={{
                ...tableStyles,
                marginBottom: '32px',
              }}
              dataSource={tableData.station}
              columns={getColumns(columns_1)}
              useVirtual={false}
            />
          ) : (
            <TRDefault type="empty" />
          )}

          <div className={styles.content_title}>合同转让收益计算及展示</div>
          {tableData?.contract?.length ? (
            <TjTable
              style={{
                ...tableStyles,
                marginBottom: '24px',
              }}
              dataSource={tableData.contract}
              columns={getColumns(columns_2)}
              useVirtual={false}
            />
          ) : (
            <TRDefault type="empty" />
          )}

          <div className={styles.content_bottom}>
            <Button className={styles.content_bottom_btn} onClick={_onClose} ghost>
              关闭
            </Button>
            <Button className={styles.content_bottom_btn} onClick={onExport} type="primary">
              导出
            </Button>
          </div>
        </div>
      )}
    </Drawer>
  );
};
class Detail {
  __key__ = '';

  show = (props) => {
    return new Promise((resolve) => {
      if (this.__key__ !== '') return;
      this.__key__ = String(Date.now());
      TRNotification.add({
        key: this.__key__,
        content: (
          <DrawerComponent
            {...props}
            onPress={(result) => {
              TRNotification.remove(this.__key__);
              this.__key__ = '';
              resolve(result);
            }}
          />
        ),
        duration: null,
      });
    });
  };

  dismiss = () => {
    if (this.__key__.length > 0) {
      TRNotification.remove(this.__key__);
      this.__key__ = '';
    }
  };
}

export default new Detail();
